// ==UserScript==
// @name         Fuck zhiniao
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Fuck the cms zhiniao
// @author       You
// @match        https://www.zhi-niao.com/znWeb/znPortal/
// @grant        none
// ==/UserScript==

var timer;

function check () {

    var bigPlayBtn = $('.vjs-big-play-button')
    var btn = $('.vjs-control-bar button')[0]

    if (btn && btn.getAttribute('title') === "Play") {
        console.log('Play click')
        $('#course-video_html5_api').click()
    }

    var courses = $('#course-video').parent().next().children('div');
    var _cources = [];

    if (courses.length) {
        for (var _i = 1; _i < courses.length; _i++) {
          var text = courses[_i].textContent
          if (text.indexOf('视频') > -1) {
            _cources.push(courses[_i]);
          }
        }
    }

    // Record current course
    var learned = 0;
    var current = 0;
    for (var i = 0; i < _cources.length; i++) {
        var div = _cources[i].getElementsByTagName('div')[0];
        div = div.getElementsByTagName('div')[0];

        if (div) {
            if (div.childNodes.length === 2) {
                learned += 1;
            }
            var span = div.getElementsByTagName('span')[0]

            if (window.getComputedStyle(span).color === 'rgb(250, 83, 74)') {
                current = i;
            }
        }
    }

    // console.log('total:', _cources.length)
    // console.log('learned:', learned)
    // console.log('current:', current)

    if (learned !== 0 && learned === _cources.length) {
        console.log('Current course is learned! Access inifity.');
        clearInterval(timer);
        timer = setInterval(function() {
            if (btn && (btn.getAttribute('title') === "Play" || btn.getAttribute('title') === "Replay")) {
                btn.click();
            }
        }, 2000);
        return false;
    }

    if (btn && btn.getAttribute('title') === "Replay") {
        console.log('Replay')
        _cources[current + 1].childNodes[0].click();
        setTimeout(() => {
            $('.vjs-big-play-button')[0].click();
            $('#course-video_html5_api').load();
        },300);
    }

}


(function() {
    'use strict';

    timer = setInterval(function() {
        check();
    }, 1000);
})();